import { reqCartList, reqDeleteCart, reqUpdataCartListIsChecked } from '@/api'
import { SET_TEMPID } from '@/utils/uuid'
const state = {
    cartListInfo: [],
    USER_ID: SET_TEMPID()
}
const mutations = {
    GETSHOPCARTLIST(state, payload) {
        state.cartListInfo = payload
    }
}
const actions = {
    // 获取购物车所有数据
    async getShopCartList({ commit }) {
        let result = await reqCartList()
        if (result.code === 200) {
            commit('GETSHOPCARTLIST', result.data)
        }
    },

    // 删除产品
    async deleteCartListBySkuId({ commit }, skuId) {
        let result = await reqDeleteCart(skuId)
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('删除产品失败！'))
        }
    },

    // 更新产品勾选状态
    async updataCartListIsById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdataCartListIsChecked(skuId, isChecked)
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('更新勾选状态失败!'))
        }
    },

    // 删除选中的商品
    deleteCartListAllByIsChecked({ dispatch, getters }) {
        let promiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            // 删除产品 肯定需要产品ID 才可知道删除哪一个产品  
            let promise = item.isChecked == 1 ? dispatch('deleteCartListBySkuId', item.skuId) : ''
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    },

    // 全部产品的勾选状态修改
    updataCartListAllByIsChecked({ dispatch, getters }, isCheckedAll) {
        let promiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            // 无需判断 只需将当前的全选勾选状态 赋予给每一个复选框（即保持同步）
            let promise = dispatch('updataCartListIsById', { skuId: item.skuId, isChecked: isCheckedAll })
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }

}
const getters = {
    // 简化出购物车产品列表数据 
    cartList() {
        return state.cartListInfo[0] || {}
    }
}
export default {
    state,
    mutations,
    actions,
    getters,
}